package com.sailing.xjpb.orm.config;

import com.sailing.xjpb.common.orm.SailingRepositoryContext;
import com.sailing.xjpb.common.sercurity.SailingUserContext;
import com.sailing.xjpb.orm.intercepter.SailingCrudRepositoryContext;
import com.sailing.xjpb.orm.intercepter.SailingTenantTableInitialization;
import com.sailing.xjpb.orm.repository.SailingRepository;
import com.sailing.xjpb.orm.repository.SailingTenantRepository;
import com.sailing.xjpb.orm.utils.SailingDefaultUserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * scppRepository自动配置类
 *
 * @author YaoWei
 * createDate: 2020/12/16
 */
@Configuration
@Slf4j
public class SailingRepositoryAutoConfiguration {

    @PersistenceContext
    private EntityManager entityManager;

    @ConditionalOnMissingBean(SailingRepository.class)
    @Bean
    public SailingRepository sailingRepository() {
        return new SailingRepository(entityManager);
    }

    @ConditionalOnMissingBean(SailingTenantRepository.class)
    @Bean
    public SailingTenantRepository tenantSailingRepository() {
        return new SailingTenantRepository(entityManager);
    }

    @ConditionalOnMissingBean(SailingUserContext.class)
    @Bean
    public SailingDefaultUserContext SailingDefaultUserContext() {
        log.info("系统未找到用户上下文BEAN,默认初始化SailingDefaultUserContext上下文！");
        return new SailingDefaultUserContext();
    }

    @Bean
    public SailingRepositoryContext sailingRepositoryContext() {
        return new SailingCrudRepositoryContext();
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SailingTenantTableInitialization sailingDataBaseInfoHandler(SailingRepository sailingRepository,
                                                                       JpaProperties jpaProperties) {
        return new SailingTenantTableInitialization(sailingRepository, jpaProperties);
    }

}
